package de.hijacksoft.isledesktopsync;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LocalizationManager {

    private static final String FILENAME = ".lang";
    
    private String file = "";
    private static LocalizationManager instance = null;
    
    private LocalizationManager(){
        
        String locale = System.getProperties().getProperty("user.language");
        
        try {
            if(!new File(locale + FILENAME).exists()) {
                System.out.println("file " + locale + FILENAME + " does not exist. using default" + FILENAME + ".");
                locale = "default";
            }
            BufferedReader in = new BufferedReader(new FileReader(locale + FILENAME));
            String str;
            while ((str = in.readLine()) != null) {
                file += str + "\n";
            }
            in.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        
        instance = this;
    }
    
    public static LocalizationManager getInstance(){
        return instance == null ? new LocalizationManager() : instance;
    }

    /**
     * This method returns a Sstring value for the given key
     * @param key the key of the setting e.g. WindowMode
     */
    public String getString(String key) throws Exception {
        String line = getLine(key);
        if(line != null){
            line = line.replaceAll(key + "=", "");
            line = line.replaceAll("\\n", "\n");
            return line;
        }
        else throw new Exception("No String found Exception! for " + key);
    }
    
    private String getLine(String key){
        // regex pattern and matcher
        Pattern p = Pattern.compile(key + "=" + ".+");
        Matcher m = p.matcher(file);
        
        if(m.find()){ // key found
            return m.group();
        }
        else return null;
    }
    
}